import { message } from 'antd';
import BraftEditor from 'braft-editor';
import React, { useEffect, useState } from 'react';

// import { BASE_URL, UPLOAD_FOLDER } from '@/constants/global.const';
import StorageManager from '@/utils/StorageManager';

import 'braft-editor/dist/index.css';

const Editor: React.FC<any> = (props) => {
  const { value, onChange } = props;

  const [editorData, setEditorData] = useState(BraftEditor.createEditorState(null));

  useEffect(() => {
    // 只需要首次value有值时，回显即可，不需要编辑器每次change都重新set
    // 编辑器每次change都会导致setEditorData重新执行，从而将光标重置到文首
    if (!editorData.isEmpty()) return;
    setEditorData(BraftEditor.createEditorState(value));
  }, [value]);

  // 编辑器内容提交之前，可直接调用editorState.toHTML()来获取HTML格式的内容
  const handleEditorChange = (editorState: {
    toText: () => any;
    isEmpty: () => any;
    toHTML: () => any;
  }) => {
    setEditorData(editorState);
    const htmlContent = editorState.toHTML();

    // 校验输入的内容是否全是空格或者换行
    const editorContent = editorState.toText().split('');
    const flag =
      editorContent.every((item: string) => ['\n', '', ' '].includes(item)) &&
      !htmlContent.includes('img');

    onChange?.(flag ? null : htmlContent);
  };

  // 在编辑器获得焦点时按下ctrl+s会执行此方法
  // const handleSaveContent = () => {
  //   const htmlContent = editorData.toHTML();
  //   onChange && onChange(htmlContent);
  // };

  // const handleUpload = (fileInfo: any) => {
  //   const XHR = new XMLHttpRequest();
  //   const formData = new FormData();

  //   const successFn = () => {
  //     const res = JSON.parse(XHR.response);
  //     if (res.code === 0) {
  //       // 上传成功后调用param.success并传入上传后的文件地址
  //       fileInfo.success({
  //         url: res.data.absoluteUrl,
  //       });
  //     } else {
  //       fileInfo.error({
  //         msg: res.errorData,
  //       });
  //     }
  //   };

  //   const progressFn = (event: { loaded: number; total: number }) => {
  //     // 上传进度发生变化时调用param.progress
  //     fileInfo.progress((event.loaded / event.total) * 100);
  //   };

  //   const errorFn = () => {
  //     // 上传发生错误时调用param.error
  //     fileInfo.error({
  //       msg: '上传失败',
  //     });
  //   };

  //   XHR.upload.addEventListener('progress', progressFn, false);
  //   XHR.addEventListener('load', successFn, false);
  //   XHR.addEventListener('error', errorFn, false);
  //   XHR.addEventListener('abort', errorFn, false);

  //   formData.append('file', fileInfo.file);
  //   formData.append('folder', UPLOAD_FOLDER.PRODUCT);

  //   XHR.open('POST', `${BASE_URL}/common/upload`, true);
  //   XHR.setRequestHeader('ticket', `${StorageManager.getCookie('token')}`);
  //   XHR.setRequestHeader('contentType', 'multipart/form-data;');
  //   XHR.send(formData);
  // };

  const handleValidate = (file: any) => {
    message.error('暂不支持添加本地媒体图片！');
    return;
    const flag = ['image/jpeg', 'image/png'].includes(file.type);
    if (!flag) message.error('格式错误');
    return flag;
  };

  return (
    <div id="braft-editor">
      <BraftEditor
        value={editorData}
        onChange={handleEditorChange}
        // onSave={handleSaveContent}
        media={{
          // uploadFn: handleUpload,
          validateFn: handleValidate,
        }}
        style={{ border: '1px solid #ccc', width: 700, marginLeft: 0 }}
      />
    </div>
  );
};

export default Editor;
